{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1d23b8bd-6016-4567-9a68-78e896d71c4b",
   "metadata": {},
   "source": [
    "# selectorGroupChat\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6317ca94-1f4c-48aa-9521-94d091e3cfcc",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Sequence\n",
    "\n",
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination\n",
    "from autogen_agentchat.messages import AgentEvent, ChatMessage\n",
    "from autogen_agentchat.teams import SelectorGroupChat\n",
    "from autogen_agentchat.ui import Console\n",
    "#from autogen_ext.models.openai import OpenAIChatCompletionClient"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "95e815c2-5ca9-481b-b13d-d9bf45928f0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from autogen_ext.models.ollama import OllamaChatCompletionClient\n",
    "import asyncio\n",
    "# Assuming your Ollama server is running locally on port 11434.\n",
    "model_client = OllamaChatCompletionClient(\n",
    "        model=\"hhao/qwen2.5-coder-tools:latest\",\n",
    "        #model=\"qwen2.5-coder:latest\",\n",
    "        #model=\"GandalfBaum/deepseek_r1-claude3.7:latest\",\n",
    "        #model = \"GandalfBaum/llama3.2-claude3.7:latest\",\n",
    "        host=\"http://192.168.99.142:11434\", \n",
    "        model_info={\n",
    "        \"vision\": False,\n",
    "        \"function_calling\": True,\n",
    "        \"json_output\": True,\n",
    "        \"family\": \"unknow\",\n",
    "        \"structed_output\":True,\n",
    "        },\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "69be03b2-ff85-4a4f-bbfe-3f7b84a583a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Note: This example uses mock tools instead of real APIs for demonstration purposes\n",
    "def search_web_tool(query: str) -> str:\n",
    "    if \"2006-2007\" in query:\n",
    "        return \"\"\"Here are the total points scored by Miami Heat players in the 2006-2007 season:\n",
    "        Udonis Haslem: 844 points\n",
    "        Dwayne Wade: 1397 points\n",
    "        James Posey: 550 points\n",
    "        ...\n",
    "        \"\"\"\n",
    "    elif \"2007-2008\" in query:\n",
    "        return \"The number of total rebounds for Dwayne Wade in the Miami Heat season 2007-2008 is 214.\"\n",
    "    elif \"2008-2009\" in query:\n",
    "        return \"The number of total rebounds for Dwayne Wade in the Miami Heat season 2008-2009 is 398.\"\n",
    "    return \"No data found.\"\n",
    "\n",
    "\n",
    "def percentage_change_tool(start: float, end: float) -> float:\n",
    "    return ((end - start) / start) * 100"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "012b411a-3571-423e-83c6-5e414e92cf07",
   "metadata": {},
   "outputs": [],
   "source": [
    "#model_client = OpenAIChatCompletionClient(model=\"gpt-4o\")\n",
    "\n",
    "planning_agent = AssistantAgent(\n",
    "    \"PlanningAgent\",\n",
    "    description=\"An agent for planning tasks, this agent should be the first to engage when given a new task.\",\n",
    "    model_client=model_client,\n",
    "    system_message=\"\"\"\n",
    "    You are a planning agent.\n",
    "    Your job is to break down complex tasks into smaller, manageable subtasks.\n",
    "    Your team members are:\n",
    "        Web search agent: Searches for information\n",
    "        Data analyst: Performs calculations\n",
    "\n",
    "    You only plan and delegate tasks - you do not execute them yourself.\n",
    "\n",
    "    When assigning tasks, use this format:\n",
    "    1. <agent> : <task>\n",
    "\n",
    "    After all tasks are complete, summarize the findings and end with \"TERMINATE\".\n",
    "    \"\"\",\n",
    ")\n",
    "\n",
    "web_search_agent = AssistantAgent(\n",
    "    \"WebSearchAgent\",\n",
    "    description=\"A web search agent.\",\n",
    "    tools=[search_web_tool],\n",
    "    model_client=model_client,\n",
    "    system_message=\"\"\"\n",
    "    You are a web search agent.\n",
    "    Your only tool is search_tool - use it to find information.\n",
    "    You make only one search call at a time.\n",
    "    Once you have the results, you never do calculations based on them.\n",
    "    \"\"\",\n",
    ")\n",
    "\n",
    "data_analyst_agent = AssistantAgent(\n",
    "    \"DataAnalystAgent\",\n",
    "    description=\"A data analyst agent. Useful for performing calculations.\",\n",
    "    model_client=model_client,\n",
    "    tools=[percentage_change_tool],\n",
    "    system_message=\"\"\"\n",
    "    You are a data analyst.\n",
    "    Given the tasks you have been assigned, you should analyze the data and provide results using the tools provided.\n",
    "    \"\"\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "18fdbe98-05b3-41e3-9108-644d2193dd85",
   "metadata": {},
   "outputs": [],
   "source": [
    "text_mention_termination = TextMentionTermination(\"TERMINATE\")\n",
    "max_messages_termination = MaxMessageTermination(max_messages=25)\n",
    "termination = text_mention_termination | max_messages_termination\n",
    "\n",
    "team = SelectorGroupChat(\n",
    "    [planning_agent, web_search_agent, data_analyst_agent],\n",
    "    model_client=model_client,\n",
    "    termination_condition=termination,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ce21aa0d-e9d3-42de-8e45-0e7ff47322e5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- user ----------\n",
      "Who was the Miami Heat player with the highest points in the 2006-2007 season, and what was the percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons?\n",
      "---------- WebSearchAgent ----------\n",
      "[FunctionCall(id='0', arguments='{\"query\": \"Miami Heat player with highest points in 2006-2007 season Miami Heat total rebounds percentage change between 2007-2008 and 2008-2009 seasons\"}', name='search_web_tool')]\n",
      "[Prompt tokens: 240, Completion tokens: 76]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Error processing publish message for WebSearchAgent/d52ed214-dcdf-48e2-82a1-6d7668ff26da\n",
      "Traceback (most recent call last):\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_core\\_single_threaded_agent_runtime.py\", line 533, in _on_message\n",
      "    return await agent.on_message(\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^\n",
      "    ...<2 lines>...\n",
      "    )\n",
      "    ^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_core\\_base_agent.py\", line 113, in on_message\n",
      "    return await self.on_message_impl(message, ctx)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_agentchat\\teams\\_group_chat\\_sequential_routed_agent.py\", line 48, in on_message_impl\n",
      "    return await super().on_message_impl(message, ctx)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_core\\_routed_agent.py\", line 485, in on_message_impl\n",
      "    return await h(self, message, ctx)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_core\\_routed_agent.py\", line 268, in wrapper\n",
      "    return_value = await func(self, message, ctx)  # type: ignore\n",
      "                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_agentchat\\teams\\_group_chat\\_chat_agent_container.py\", line 53, in handle_request\n",
      "    async for msg in self._agent.on_messages_stream(self._message_buffer, ctx.cancellation_token):\n",
      "    ...<11 lines>...\n",
      "            )\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_agentchat\\agents\\_assistant_agent.py\", line 367, in on_messages_stream\n",
      "    results = await asyncio.gather(*[self._execute_tool_call(call, cancellation_token) for call in result.content])\n",
      "              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\autogen_agentchat\\agents\\_assistant_agent.py\", line 437, in _execute_tool_call\n",
      "    return FunctionExecutionResult(content=f\"Error: {e}\", call_id=tool_call.id)\n",
      "  File \"E:\\pythonShop\\pythonLangChain\\Lib\\site-packages\\pydantic\\main.py\", line 214, in __init__\n",
      "    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)\n",
      "pydantic_core._pydantic_core.ValidationError: 1 validation error for FunctionExecutionResult\n",
      "name\n",
      "  Field required [type=missing, input_value={'content': \"Error: 1 val...issing\", 'call_id': '0'}, input_type=dict]\n",
      "    For further information visit https://errors.pydantic.dev/2.10/v/missing\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- Summary ----------\n",
      "Number of messages: 2\n",
      "Finish reason: None\n",
      "Total prompt tokens: 240\n",
      "Total completion tokens: 76\n",
      "Duration: 3.78 seconds\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "TaskResult(messages=[TextMessage(source='user', models_usage=None, content='Who was the Miami Heat player with the highest points in the 2006-2007 season, and what was the percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons?', type='TextMessage'), ToolCallRequestEvent(source='WebSearchAgent', models_usage=RequestUsage(prompt_tokens=240, completion_tokens=76), content=[FunctionCall(id='0', arguments='{\"query\": \"Miami Heat player with highest points in 2006-2007 season Miami Heat total rebounds percentage change between 2007-2008 and 2008-2009 seasons\"}', name='search_web_tool')], type='ToolCallRequestEvent')], stop_reason=None)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "task = \"Who was the Miami Heat player with the highest points in the 2006-2007 season, and what was the percentage change in his total rebounds between the 2007-2008 and 2008-2009 seasons?\"\n",
    "\n",
    "# Use asyncio.run(...) if you are running this in a script.\n",
    "await Console(team.run_stream(task=task))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45fb2d6f-ef3b-46bf-b0d6-9e6ee5fc4488",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
